package com.yang.biz.modular.http.manager;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yang.biz.modular.http.util.HttpResponseUtil;

/**
 * @author: yangjianzhi
 * @version1.0
 */
public class CustomHttpRequest {

    protected String baseURL;

    private HttpRequest httpRequest;

    private String token;

    public CustomHttpRequest get(String url) {
        this.httpRequest = HttpRequest.get(baseURL + url);
        return this;
    }

    public CustomHttpRequest post(String url) {
        this.httpRequest = HttpRequest.post(baseURL + url);
        return this;
    }

    /**
     * 添加自定义方法，比如设置请求头、请求参数等...
     */
    public CustomHttpRequest header(String name, String value) {
        httpRequest.header(name, value);
        return this;
    }

    public CustomHttpRequest form(String name, Object value) {
        httpRequest.form(name, value);
        return this;
    }

    public CustomHttpRequest body(String name, Object value, Object... parameters) {
        JSONObject bodyObj = JSONUtil.createObj().set(name, value);

        for (int i = 0; i < parameters.length; i += 2) {
            bodyObj.set(parameters[i].toString(), parameters[i + 1]);
        }
        httpRequest.body(bodyObj.toString());
        return this;
    }

    private HttpResponse execute() {
        if (StrUtil.isNotBlank(token)) {
            this.header("token", token);
        }
        this.token = "";
        return this.httpRequest.execute();
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Boolean executeBoolean() {
        return HttpResponseUtil.handleRequestResult(this.execute().body(),
                this.httpRequest.getUrl());
    }

    public JSONArray executeArray() {
        return HttpResponseUtil.getResponseDataArr(this.execute().body(),
                this.httpRequest.getUrl());
    }

    public JSONObject executeObject() {
        return HttpResponseUtil.getResponseData(this.execute().body(),
                this.httpRequest.getUrl());
    }
}
